<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="职称" prop="title" style="width: 200px;">
        <el-select v-model="queryParams.title" placeholder="请选择职称" clearable>
          <el-option
              v-for="dict in counselor_titles"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="认证状态" prop="certificationStatus" style="width: 200px;">
        <el-select v-model="queryParams.certificationStatus" placeholder="请选择认证状态" clearable>
          <el-option
              v-for="dict in certification_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['counselor:counselor:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['counselor:counselor:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="咨询师ID" align="center" prop="counselorId"/>
      <el-table-column label="咨询师姓名" align="center" prop="userName"/>
      <el-table-column label="职称" align="center" prop="title">
        <template #default="scope">
          <dict-tag :options="counselor_titles" :value="scope.row.title"/>
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center" prop="sex">
        <template #default="scope">
          <dict-tag :options="sys_user_sex" :value="scope.row.sex"/>
        </template>
      </el-table-column>
      <el-table-column label="头像" align="center" prop="avatar" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.avatar" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="擅长领域" align="center" prop="expertise"/>
      <el-table-column label="预约地址" align="center" prop="address"/>
      <el-table-column label="认证状态" align="center" prop="certificationStatus">
        <template #default="scope">
          <dict-tag :options="certification_status" :value="scope.row.certificationStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['counselor:counselor:edit']">审 核
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改咨询师信息对话框 -->
    <el-dialog :title="title" v-model="open" :rules="rules" width="900px" append-to-body>
      <el-form ref="counselorRef" :model="form" label-width="120px" size="large">
        <el-row :gutter="30">
          <!-- 左边基本信息 -->
          <el-col :span="12">
            <el-card shadow="never" header="基本信息">
              <el-form-item label="申请人名称">
                <el-input v-model="form.userName" disabled/>
              </el-form-item>
              <el-form-item label="性别">
                <dict-tag :options="sys_user_sex" :value="form.sex" disabled/>
              </el-form-item>
              <el-form-item label="手机号">
                <el-input v-model="form.phonenumber" disabled/>
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="form.email" disabled/>
              </el-form-item>
              <el-form-item label="头像">
                <image-preview :src="form.avatar" :width="100" :height="100" disabled/>
              </el-form-item>
              <el-form-item label="预约地址" prop="address">
                <el-input v-model="form.address" type="textarea" rows="4" disabled/>
              </el-form-item>
            </el-card>
          </el-col>

          <!-- 右边申请信息 -->
          <el-col :span="12">
            <el-card shadow="never" header="申请信息">
              <el-form-item label="职称" prop="title">
                <el-select v-model="form.title" placeholder="请选择职称" disabled>
                  <el-option
                      v-for="dict in counselor_titles"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"/>
                </el-select>
              </el-form-item>
              <el-form-item label="简介/专业背景" prop="bio">
                <el-input v-model="form.bio" type="textarea" rows="4" disabled/>
              </el-form-item>
              <el-form-item label="擅长领域" prop="expertise">
                <el-input v-model="form.expertise" type="textarea" rows="4" disabled/>
              </el-form-item>
              <el-form-item label="相关证书" prop="certification">
                <image-preview :src="form.certification"></image-preview>
              </el-form-item>

              <el-form-item label="是否通过" prop="expertise">
                <el-radio-group v-model="form.certificationStatus">
                  <el-radio-button
                      v-for="dict in certification_status.filter(item => item.value !== '0')"
                      :label="dict.label"
                      :value="dict.value"
                  >
                  </el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="未通过原因" prop="reason" v-show="form.certificationStatus === '2'">
                <el-input v-model="form.reason" placeholder="请输入未通过原因"/>
              </el-form-item>
            </el-card>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Counselor">
import {getCounselor, handleApplyFor, listCounselor} from "@/api/counselor/counselor";
import ImagePreview from "@/components/ImagePreview/index.vue";

const {proxy} = getCurrentInstance();
const {
  certification_status,
  counselor_titles,
  sys_user_sex,
} = proxy.useDict('certification_status', 'counselor_titles', 'sys_user_sex');

const dataList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: null,
    certificationStatus: null,
    reason: null,
  },
  rules: {
    title: [
      {required: true, message: "职称不能为空", trigger: "change"}
    ],
    certificationStatus: [
      {required: true, message: "请选择认证状态", trigger: "change"}
    ],
    reason: [
      {
        required: () => form.value.certificationStatus === '2',
        message: "未通过原因不能为空",
        trigger: 'blur'
      }
    ]
  }
});

const {queryParams, form, rules} = toRefs(data);

/** 提交表单 */
function submitForm() {
  proxy.$refs["counselorRef"].validate(valid => {
    if (valid) {
      let submitData = {
        userId: form.value.userId,
        certificationStatus: form.value.certificationStatus,
      }
      if (form.value.certificationStatus === '2') {
        submitData.reason = form.value.reason;
      }
      handleApplyFor(submitData).then(res => {
        if (res.code === 200) {
          open.value = false;
          proxy.$modal.msgSuccess("审核成功！");
          getList();
        }
      }).catch(err => {
        open.value = false;
        proxy.$modal.msgError(err.message);
      })
    }
  });
}

/** 查询咨询师信息列表 */
function getList() {
  loading.value = true;
  listCounselor(queryParams.value).then(res => {
    // 合并逻辑
    dataList.value = res.data.counselorList.map(counselor => {
      const user = res.data.userList.find(u => u.userId === counselor.userId)
      return {
        ...counselor,
        ...user, // 合并用户信息
      }
    })
    total.value = dataList.value.length;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    counselorId: null,
    userId: null,
    title: null,
    bio: null,
    expertise: null,
    address: null,
    certification: null,
    certificationStatus: null,
    reason: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null
  };
  proxy.resetForm("counselorRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.counselorId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加咨询师信息";
}

/** 审核按钮操作 */
function handleUpdate(row) {
  reset();
  getCounselor(row.counselorId).then(response => {
    console.log("咨询师详细信息",response)
    // 合并用户数据到form
    form.value = {
      ...response.data,
      ...dataList.value.find(item => item.counselorId === row.counselorId)
    };
    console.log("合并后的form",form.value)
    open.value = true;
    title.value = "审核咨询师信息";
  });
}


/** 导出按钮操作 */
function handleExport() {
  proxy.download('counselor/counselor/export', {
    ...queryParams.value
  }, `counselor_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  getList();
})
</script>
